package main

import (
	"less_day/internal/config"
	"less_day/internal/handler"
	"less_day/internal/middleware"
	"less_day/internal/utils"
	"less_day/pkg/database"
	"less_day/pkg/redis"
	"log"

	"github.com/gin-gonic/gin"
)

func main() {
	// 加载配置
	cfg, err := config.LoadConfig()
	if err != nil {
		log.Fatal("Failed to load config:", err)
	}

	// 初始化数据库
	db, err := database.InitMySQL(cfg.Database)
	if err != nil {
		log.Fatal("Failed to connect to database:", err)
	}

	// 初始化Redis
	rdb := redis.InitRedis(cfg.Redis)

	// 设置Gin模式
	if cfg.Server.Mode == "release" {
		gin.SetMode(gin.ReleaseMode)
	}

	// 创建Gin引擎
	r := gin.Default()

	// 中间件
	r.Use(middleware.Logger())
	r.Use(middleware.CORS())

	// 初始化处理器
	userHandler := handler.NewUserHandler(db, rdb)
	checkinHandler := handler.NewCheckInHandler(db, rdb)
	statisticsHandler := handler.NewStatisticsHandler(db, rdb)
	debugHandler := handler.NewDebugHandler(db, rdb)

	// API路由组
	api := r.Group("/api/v1")
	{
		// 认证相关
		auth := api.Group("/auth")
		{
			auth.POST("/wechat-login", userHandler.WechatLogin)
			auth.Use(middleware.JWTAuth()).POST("/phone-login", userHandler.PhoneLogin)
		}

		// 用户相关
		users := api.Group("/users")
		users.Use(middleware.JWTAuth())
		{
			users.GET("/profile", userHandler.GetProfile)
			users.PUT("/profile", userHandler.UpdateProfile)
		}

		// 打卡相关
		checkin := api.Group("/checkin")
		checkin.Use(middleware.JWTAuth())
		{
			checkin.POST("", checkinHandler.CreateCheckIn)
			checkin.GET("/today", checkinHandler.GetTodayCheckIn)
			checkin.GET("/list", checkinHandler.GetCheckInList)
			checkin.PUT("/:id", checkinHandler.UpdateCheckIn)
			checkin.DELETE("/:id", checkinHandler.DeleteCheckIn)
		}

		// 统计相关
		stats := api.Group("/statistics")
		stats.Use(middleware.JWTAuth())
		{
			stats.GET("/overview", statisticsHandler.GetOverview)
			stats.GET("/calendar", statisticsHandler.GetCalendar)
			stats.GET("/trend", statisticsHandler.GetTrend)
			stats.GET("/category", statisticsHandler.GetCategoryStats)
		}
	}

	// 调试接口（仅在开发模式启用）
	if cfg.Server.Mode == "debug" {
		debug := r.Group("/debug")
		{
			debug.POST("/wechat-login", debugHandler.TestWechatLogin)
			debug.GET("/config", debugHandler.CheckConfig)
			debug.GET("/validate", func(c *gin.Context) {
				if err := utils.ValidateConfig(); err != nil {
					c.JSON(400, gin.H{"error": err.Error()})
				} else {
					c.JSON(200, gin.H{"message": "配置验证通过"})
				}
			})
		}
	}

	// 健康检查
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"status":  "ok",
			"message": "Less Day API is running",
		})
	})

	log.Printf("Server starting on port %s", cfg.Server.Port)
	if err := r.Run(":" + cfg.Server.Port); err != nil {
		log.Fatal("Failed to start server:", err)
	}
}
